import FormItemType from "../FormItemType";
import FormItem from "../FormItem";
import Label from "../FormLabel";
import {connect} from "react-redux";
import FormGroup from "../FormGroup";
import InputGroup from "../InputGroup";
import Canlendar from "../canlendar";
import {URL} from './../../libs/Url';
import {Fetch_} from './../../libs/';
import {fetchUser} from './../../actions/';
const Lesson = React.createClass({
    getDefaultProps(){
        return {
            onchange: (val)=> {
                console.log(val)
            }
        };
    },
    getInitialState(){
        const self = this;
        const onchange = (index, content) => {
            self.setState({
                form: [
                    ...self.state.form.slice(0, index),
                    Object.assign({}, self.state.form[index], {
                        value: content,
                        tips: content.length ? '' : '该项必填',
                    }),
                    ...self.state.form.slice(index + 1),
                ]
            });
        };
        this.form = [
            {
                label: '计划名称',
                value: '',
                name: 'name',
                required: true,
                onchange: onchange
            },
            {
                label: '计划详情',
                value: '',
                name: 'comment',
                required: true,
                type: FormItemType.EDITOR,
                onchange: onchange,
            },
            {
                label: '相关附件',
                value: '',
                name: 'fileids',
                type: FormItemType.UPLOAD,
                onchange: onchange
            },

        ];
        console.log('init');
        return {
            canlender: false,
            form: this.cloneArray(this.form),
            schedules: {},
            user: {
                ['selected_class']: []
            },
            selected: {}//已选择课程
        }
    },

    cloneArray(arr){
        var self = this;
        return arr.map(item=> {
            return self.deepClone(item);
        });
    },
    deepClone(obj) {
        var self = this;
        var o = obj instanceof Array ? [] : {};
        for (var k in obj)
            o[k] = typeof obj[k] === Object ? self.deepClone(obj[k]) : obj[k];
        return o;
    },
    componentWillReceiveProps(nextProps){
        if (nextProps['user']) {
            this.setState({
                user: nextProps['user'],
            })
        }

        if (nextProps.status == 'add' && this.state.type != 'add') {
            this.setState({
                type: 'add',
                form: this.cloneArray(this.form)
            })
        }
        if (nextProps.status == 'update' && this.state.type != 'update') {
            this.setState({
                type: 'update',
                form: this.cloneArray(this.form).map((item, index)=> {
                    var item_ = nextProps.item || {};
                    item.value = item_[item.name] || '';
                    return item;
                })
            })
        }
    },
    componentDidMount(){
        const {user, dispatch} = this.props, self = this;
        if (user && (user['class'] instanceof Array)) {
            var schedules = [];
            user['class'].forEach(item=> {
                schedules.push(Fetch_(URL.SCHEDULE_GET, {body: {classid: item.classid}}))
            });
            Promise.all(schedules)
                .then(res=> {
                    var schedule = {};
                    res.slice(0, user['class'].length).forEach((item, index)=> {
                        schedule[user['class'][index].classid] = Object.assign({}, {
                            list: item.list,
                            classInfo: user['class'][index]
                        }, {
                            selected: {},
                            tmp: {},
                        });
                    });
                    // var last = res[res.length - 1].homework;
                    self.setState({
                        schedules: schedule
                    });
                })
                .catch(e=> {
                    console.log(e);
                })
        } else {
            Fetch_(URL.Get_USER_CLASS)
                .then(res=> {
                    var schedule = {};
                    var schedules = [];
                    res.list.forEach(item=> {
                        schedules.push(Fetch_(URL.SCHEDULE_GET, {body: {classid: item.classid}}))
                    });
                    var res_ = res;
                    Promise.all(schedules)
                        .then(res=> {
                            var schedule = {};
                            res.slice(0, res_.list.length).forEach((item, index)=> {
                                schedule[res_.list[index].classid] = Object.assign({}, {
                                    list: item.list,
                                    classInfo: res_.list[index]
                                }, {
                                    selected: {},
                                    tmp: {},
                                });
                            });
                            // var last = res[res.length - 1].homework;
                            self.setState({
                                schedules: schedule
                            });
                        })
                        .catch(e=> {
                            console.log(e);
                        })
                })
                .catch(e=> {
                    console.log(e)
                })
        }

    },
    submit(){
        let form = {};
        this.state.form.forEach((item=> {
            form[item.name] = item.value;
        }));
        let courseList = [];
        this.state.user['class'].forEach((item)=> {
            let item_ = {};
            item_.teachid = item.teachid;
            item_.class_ = item;
            // console.log(item);
            if (this.state.schedules[item.classid].selected) {
                item_.time = Object.keys(this.state.schedules[item.classid].selected || {}).toString();
                courseList.push(item_);
            }
        });
        if (this.state.type == 'update') {
            form.courseid = this.props.item.courseid;
        }
        form.courseList = (courseList);
        this.props.onconfirm(form);
    },
    render(){
        const self = this;
        var class_ = this.state.user['class'] || [];
        var type = this.props.status;
        var form = self.state.form;

        return <div className="form-horizontal">
            {
                form.map((item, index)=> {
                    item.index = index;
                    return <FormItem key={index} {...item}></FormItem>
                })
            }
            <hr/>
            <FormGroup>
                <Label>设置推送时间</Label>
                <InputGroup>
                    <ul className="homeword-set">
                        {class_.map((item, index)=> {
                            item.date = {};
                            var time = self.state.schedules[item.classid] ? (self.state.schedules[item.classid].selected || {}) : {};
                            return <li key={index}>
                                <b>{item['class'].name}</b>
                                <span
                                    className="text-success">{
                                    Object.keys(time) || '未设置'}</span>
                                <span className="pull-right">
                                <button
                                    className="btn btn-default btn-xs"
                                    onClick={()=> {
                                        if (self.state.schedules[item.classid].list.timetable.length == 0) {
                                            return alert('该班级还未设置课程表');
                                        }

                                        self.setState({
                                            current: item.classid,
                                            canlender: true,
                                        });
                                    }}
                                >
                                    <i className="fa fa-window-restore"></i> 设置推送时间
                                </button>
                            </span>
                            </li>
                        })}
                    </ul>
                </InputGroup>
            </FormGroup>
            {
                self.state.canlender ? <div style={{
                    position: 'absolute',
                    top: -45,
                    bottom: -72,
                    left: 0,
                    zIndex: 9999999,
                    right: 0, padding: 15,
                    background: '#FFF'
                }}>
                    <br/>
                    <br/>
                    <Canlendar
                        classInfo={self.state.schedules[self.state.current]}
                        onchange={(data)=> {
                            self.props.onchange(data);
                            self.setState({
                                selected: data,
                            });
                        }}
                        multiSelect={false}
                        selected={self.state.selected ||  {}}
                    />
                    <div>
                        <div className="btn btn-primary btn-sm"
                             onClick={()=> {
                                 let selected = Object.assign({}, self.state.selected || {});
                                 self.setState({
                                     canlender: false,
                                     schedules: Object.assign({}, self.state.schedules, {
                                         [self.state.current]: Object.assign({}, self.state.schedules[self.state.current], {
                                             selected: self.state.selected
                                         })
                                     }),

                                     selected: ''
                                 });
                             }}
                        >确定
                        </div>
                    </div>
                </div> : ''
            }
            <div>
                <button type="button" onClick={()=> {
                    this.submit();
                }} className="btn btn-primary">保存
                </button>
            </div>
        </div>
    }
})


function select(state) {
    return {}
}
// export default Lesson;
export default connect(select)(Lesson)